﻿using System.Globalization;
using System.Windows.Controls;

namespace DimensionsHelper.Client.ValidationRules;

public class DoubleRangeValidationRule : ValidationRule
{
    public double UpperBoundary { get; set; }

    public double LowerBoundary { get; set; }

    public bool IsClosedBoundary { get; set; }


    public override ValidationResult Validate(object? value, CultureInfo cultureInfo)
    {
        double? dbVal = value switch
        {
            string str when double.TryParse(str, out double dNum) => dNum,
            double num => num,
            _ => null
        };

        if (dbVal != null)
        {
            if ((IsClosedBoundary && dbVal >= LowerBoundary && dbVal <= UpperBoundary) ||
                (!IsClosedBoundary && dbVal > LowerBoundary && dbVal < UpperBoundary))
            {
                return ValidationResult.ValidResult;
            }
        }

        return new ValidationResult(false,
            $"值{value}无效，应为区间'{(IsClosedBoundary ? "[" : "(")}{LowerBoundary}..{UpperBoundary}{(IsClosedBoundary ? "]" : ")")}'内的实数。");
    }
}